package day9;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.Test;

public class ExceptionDemo {

	@Test
	public void test1() {
		Student student = null;
		System.out.println(student);// null
		// null.属性  null.方法 会报空指针异常 NullPointerException  NPE
		if (student != null) {
			System.out.println(student.getAge());
		}
		
		// java.lang.StringIndexOutOfBoundsException: String index out of range: 5
		String str = "hello";
		// System.out.println(str.charAt(5));
		
		int i = 3;
		// java.lang.ArithmeticException: / by zero
		//System.out.println(i / 0);
		
		// System.out.println("------------");
		student = new Student();
		Person person = new Person();
		// java.lang.ClassCastException: day9.Person cannot be cast to day9.Student
		student = (Student) person;
	}
	
	
	@Test
	public void test2() {
		// Unhandled exception type FileNotFoundException
		// 编译时异常：写代码时候就会抛出的异常，如果不去处理就会报错
		try { // try里面包含的是"可能"会抛出异常的代码
			FileInputStream fileInputStream = new FileInputStream("a.txt");
		} catch (FileNotFoundException e){//如果代码抛出异常就会执行catch里面的代码
			e.printStackTrace();
		} finally {
			// 一定会被执行的代码（不管异常抛不抛出都会执行）
			// 主要用来关闭连接、释放资源
			System.out.println("----finally-----");
		}
		// 即使抛出了异常，catch里面会捕获，程序不会崩溃，后面的可以继续执行
		System.out.println("--------");
	}
	
	@Test
	public void test3() throws FileNotFoundException {
		handleException();
	}
	
	public void handleException() throws FileNotFoundException  {
			FileInputStream fileInputStream = new FileInputStream("a.txt");
	}
	
	@Test
	public void test4() {
		FileInputStream fileInputStream;
		try {
			fileInputStream = new FileInputStream("a.txt");
			fileInputStream.read();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Unreachable catch block for FileNotFoundException. 
		// It is already handled by the catch block for IOException
	}
	
	@Test
	public void test5() {
		AccountManager accountManager = new AccountManager(1000.0);
		// accountManager.withdraw(3434.0);
		try {
			accountManager.withdraw(1200.0);
		} catch (MeiQianException e) {
			e.printStackTrace();
		}
		System.out.println("==============");
	}
	
	
	@Test
	public void test6() {
		int num = fun();
	}


	private int fun() {
		try {
			return 3;
		} catch (Exception e) {
		} finally {
			System.out.println("---finally-----");
		}
		return 0;
	}
	
	
	
	
	
}
